package com.mbl.base.core.utils;

import com.mbl.base.config.security.SecurityUser;
import com.mbl.base.config.security.UserDetailServiceImpl;
import com.mbl.base.modular.member.entity.User;
import com.mbl.base.modular.member.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class UtilSecurity {

    /**
     * 根据token缓存用户信息
     */
    private static Map<String, SecurityUser> securityUserOfTokenMap = new HashMap<>();
    private static UserDetailServiceImpl userDetailService;
    private static IUserService userService;
    public UtilSecurity(UserDetailServiceImpl userDetailService, IUserService userService){
        this.userDetailService = userDetailService;
        this.userService = userService;
    }

    /**
     * 获取用户信息
     * @return
     */
    public static SecurityUser getUser(){
        try {
            String token = UtilToken.getToken();
            SecurityUser securityUser1 = securityUserOfTokenMap.get(token);
            if(securityUser1 != null){
                return securityUser1;
            }
            String userName = UtilToken.getUserName();
            if(StringUtils.isBlank(userName)){
                return null;
            }
            SecurityUser securityUser = (SecurityUser) userDetailService.loadUserByUsername(userName);
            securityUserOfTokenMap.put(token, securityUser);
            return securityUser;
        } catch (Exception e){
            return null;
        }
    }

    /**
     * 获取数据库user对象
     * @return
     */
    public static User getDoUser(){
        final SecurityUser user = getUser();
        if(user != null){
            return userService.getById(user.getId());
        }
        return null;
    }

}
